<template>
  <div class="setup-menu-container">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form inline :model="searchData">
        <el-form-item label="菜单名称">
          <el-input
            v-model="searchData.permissionName"
            placeholder="请输入菜单名称"
            style="width: 200px"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" @click="handleAdd(1)">新增父级目录</el-button>
          <el-button type="success" @click="handleAdd(2)">新增子级菜单</el-button>
          <el-button type="success" @click="handleAdd(3)">新增子级按钮</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 菜单表格 -->
    <art-table
      ref="tableRef"
      :data="tableData"
      :loading="loading"
      :pagination="true"
      :total="total"
      :current-page="searchData.page"
      :page-size="searchData.pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      highlight-current-row
      show-header-background
      row-key="permissionId"
      border
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      @select="handleSelect"
      @select-all="handleSelectAll"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="permissionName" label="菜单名称" min-width="150" />
      <el-table-column label="图标" width="80">
        <template #default="scope">
          <icon :icon="scope.row.icon" v-if="scope.row.icon" />
        </template>
      </el-table-column>
      <el-table-column prop="permission" label="菜单标识" min-width="150" />
      <el-table-column prop="createTime" label="创建时间" min-width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <div class="table-actions">
            <button-table type="edit" @click="handleEdit(scope.row)" />
            <el-popconfirm title="确认删除此菜单吗？" @confirm="handleDelete(scope.row)">
              <template #reference>
                <button-table type="delete" @click.stop="() => {}" />
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </art-table>

    <!-- 新增/编辑菜单对话框 -->
    <el-dialog
      v-model="menuDialogVisible"
      :title="isEdit ? '编辑菜单' : '新增菜单'"
      width="30%"
      center
      :close-on-click-modal="false"
      @closed="onMenuDialogClosed"
    >
      <el-form ref="menuFormRef" :model="menuForm" label-width="80px" :rules="menuFormRules">
        <el-form-item label="父节点ID" prop="permissionPid">
          <el-input v-model="menuForm.permissionPid" maxlength="20" :disabled="true" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="permissionName">
          <el-input v-model="menuForm.permissionName" placeholder="请输入菜单名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="permission">
          <el-input v-model="menuForm.permission" placeholder="请输入菜单路径" maxlength="100" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <Icons
            :default-icon="menuForm.icon"
            @get-icon="(icon) => (menuForm.icon = icon)"
            text="选择图标"
            width="100%"
          />
        </el-form-item>
        <el-form-item label="菜单描述" prop="describe">
          <el-input v-model="menuForm.describe" placeholder="请输入菜单描述" maxlength="60" />
        </el-form-item>
        <el-form-item label="排序值" prop="sort">
          <el-input
            v-model="menuForm.sort"
            placeholder="请输入排序值"
            maxlength="9"
            oninput="value=value.replace(/[^\d]/g,'')"
          />
        </el-form-item>
        <el-form-item label="权限类型" prop="resourceType">
          <el-select v-model="menuForm.resourceType" placeholder="请选择权限类型">
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
            <el-option label="目录" value="catalog" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="menuDialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="handleMenuSubmit"
            >确定</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, onMounted, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { SetupService } from '@/api/setupApi'
  import Icons from '@/components/Icons/IconSelector.vue'

  // 表格引用
  const tableRef = ref(null)
  const menuFormRef = ref(null)

  // 加载状态
  const loading = ref(false)
  const submitLoading = ref(false)
  import { ApiStatus } from '@/utils/http/status'

  // 搜索数据 - 添加明确的类型注解
  const searchData = ref({
    permissionName: '',
    page: 1,
    pageSize: 10
  })

  // 表格数据
  const total = ref(0)
  const tableData = ref([])
  const multipleSelection = ref([])

  // 对话框状态
  const menuDialogVisible = ref(false)
  const isEdit = ref(false)

  // 表单数据
  const menuForm = ref({
    permissionId: '', // 菜单ID
    permissionPid: '', // 父节点ID
    permissionName: '', // 菜单名称
    permissionUri: '', // URI
    permission: '', // 组件路径
    icon: '', // 图标
    describe: '', // 描述
    resourceType: 'menu', // 权限类型 menu-菜单 button-按钮 catalog-目录
    sort: '' // 排序值
  })

  // 表单验证规则
  const menuFormRules = ref({
    permissionName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    permission: [{ required: true, message: '请输入菜单路径', trigger: 'blur' }],
    resourceType: [{ required: true, message: '请选择权限类型', trigger: 'change' }],
    sort: [{ required: true, message: '请输入排序值', trigger: 'blur' }],
    icon: [{ required: true, message: '请选择图标', trigger: 'blur' }]
  })

  // 生命周期
  onMounted(() => {
    getMenuList()
  })

  // 处理选择变化
  const handleSelectionChange = (val) => {
    multipleSelection.value = val
  }

  // 设置子节点选中状态
  const setChildren = (children, type) => {
    children.forEach((child) => {
      toggleSelection(child, type)
      if (child.children) {
        setChildren(child.children, type)
      }
    })
  }

  // 处理选择
  const handleSelect = (selection, row) => {
    if (selection.some((el) => row.permissionId === el.permissionId)) {
      // 选中当前行
      if (row.children) {
        setChildren(row.children, true)
      }
    } else {
      // 取消选中当前行
      if (row.children) {
        setChildren(row.children, false)
      }
    }
  }

  // 处理全选
  const handleSelectAll = (selection) => {
    // 检查是否全选
    const isSelect = selection.some((el) => {
      const tableDataIds = tableData.value.map((item) => item.permissionId)
      return tableDataIds.includes(el.permissionId)
    })

    // 检查是否取消全选
    const isCancel = !tableData.value.every((el) => {
      const selectIds = selection.map((item) => item.permissionId)
      return selectIds.includes(el.permissionId)
    })

    if (isSelect) {
      selection.forEach((el) => {
        if (el.children) {
          setChildren(el.children, true)
        }
      })
    }

    if (isCancel) {
      tableData.value.forEach((el) => {
        if (el.children) {
          setChildren(el.children, false)
        }
      })
    }
  }

  // 分页大小变化
  const handleSizeChange = (val) => {
    searchData.value.pageSize = val
    getMenuList()
  }

  // 页码变化
  const handleCurrentChange = (val) => {
    searchData.value.page = val
    getMenuList()
  }

  // 搜索
  const handleSearch = () => {
    total.value = 0
    searchData.value.page = 1
    getMenuList()
  }

  // 重置搜索
  const handleReset = () => {
    searchData.value = {
      permissionName: '',
      page: 1,
      pageSize: 10
    }
    getMenuList()
  }

  // 新增菜单
  const handleAdd = (type) => {
    isEdit.value = false

    // 直接使用模拟数据替代API调用，确保弹窗能正常显示
    const mockMaxSort = 100 // 模拟的最大排序值

    if (type === 1) {
      // 新增父级目录
      if (multipleSelection.value.length >= 1) {
        return ElMessage({ message: '请勿选择节点进行操作' })
      }
      menuForm.value.permissionPid = ''
      menuForm.value.resourceType = 'catalog'
      menuForm.value.sort = mockMaxSort
      menuDialogVisible.value = true
    } else if (type === 2) {
      // 新增子级菜单
      if (multipleSelection.value.length === 0) {
        return ElMessage({ message: '请选择父节点' })
      }
      if (multipleSelection.value[0].permissionPid !== 0) {
        return ElMessage({ message: '请选择顶级节点进行操作' })
      }
      menuForm.value.permissionPid = multipleSelection.value[0].permissionId
      menuForm.value.resourceType = 'menu'
      menuForm.value.sort = mockMaxSort
      menuDialogVisible.value = true
    } else if (type === 3) {
      // 新增子级按钮
      if (multipleSelection.value.length === 0) {
        return ElMessage({ message: '请选择父节点' })
      }
      if (
        multipleSelection.value[0].permissionPid === 0 &&
        multipleSelection.value[0].children &&
        multipleSelection.value[0].children.length > 0
      ) {
        return ElMessage({ message: '请勿选择顶级节点进行操作' })
      }
      menuForm.value.permissionPid = multipleSelection.value[0].permissionId
      menuForm.value.resourceType = 'button'
      menuForm.value.sort = mockMaxSort
      menuDialogVisible.value = true
    }
  }

  // 编辑菜单
  const handleEdit = (row) => {
    isEdit.value = true
    menuDialogVisible.value = true

    // 获取菜单详情
    SetupService.tabsGetById({ permissionId: row.permissionId })
      .then((res) => {
        menuForm.value = { ...res.data }
      })
      .catch((error) => {
        console.error('获取菜单详情失败:', error)
        ElMessage({ message: '获取菜单详情失败', type: 'error' })
      })
  }

  // 删除菜单
  const handleDelete = (row) => {
    ElMessageBox.confirm('此操作将永久删除该菜单及其子菜单，是否继续？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        SetupService.tabsDelete({ permissionId: row.permissionId })
          .then((res) => {
            if (res.code === ApiStatus.success) {
              ElMessage({ message: '删除成功', type: 'success' })
              getMenuList()
            } else {
              ElMessage({ message: res.message || '删除失败', type: 'error' })
            }
          })
          .catch((error) => {
            console.error('删除菜单失败:', error)
            ElMessage({ message: '删除失败', type: 'error' })
          })
      })
      .catch(() => {
        // 用户取消删除
      })
  }

  // 处理菜单提交
  const handleMenuSubmit = async () => {
    if (!menuFormRef.value) return

    try {
      await menuFormRef.value.validate()
      submitLoading.value = true

      if (isEdit.value) {
        // 编辑菜单
        const res = await SetupService.tabsUpdate(menuForm.value)
        if (res.code === ApiStatus.success) {
          ElMessage({ message: '修改成功', type: 'success' })
          menuDialogVisible.value = false
          getMenuList()
        } else {
          ElMessage({ message: res.message || '修改失败', type: 'error' })
        }
      } else {
        // 新增菜单
        const res = await SetupService.tabsAdd(menuForm.value)
        if (res.code === ApiStatus.success) {
          ElMessage({ message: '新增成功', type: 'success' })
          menuDialogVisible.value = false
          getMenuList()
        } else {
          ElMessage({ message: res.message || '新增失败', type: 'error' })
        }
      }
    } catch (error) {
      console.error('菜单提交失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  // 菜单对话框关闭时重置表单
  const onMenuDialogClosed = () => {
    menuForm.value = {
      permissionId: '',
      permissionPid: '',
      permissionName: '',
      permissionUri: '',
      permission: '',
      icon: '',
      describe: '',
      resourceType: 'menu',
      sort: ''
    }
    if (menuFormRef.value) {
      menuFormRef.value.resetFields()
    }
  }

  // 获取菜单列表
  const getMenuList = async () => {
    try {
      loading.value = true
      const res = await SetupService.tabsGetAll(searchData.value)
      console.log('API返回的原始数据:', res) // 调试信息
      if (res.code === ApiStatus.success) {
        let menuData = res.data.list || []
        total.value = res.data.total || 0

        // 将childs字段转换为children字段以适配el-tree组件
        const convertChildsToChildren = (data) => {
          return data.map((item) => {
            const newItem = { ...item }
            if (newItem.childs) {
              newItem.children = convertChildsToChildren(newItem.childs)
              delete newItem.childs
            }
            return newItem
          })
        }

        // 转换数据结构
        menuData = convertChildsToChildren(menuData)
        console.log('转换后的菜单数据:', menuData) // 调试信息
        tableData.value = menuData

        // 如果没有查询到数据，提供假数据
        if (!tableData.value || tableData.value.length === 0) {
          tableData.value = [
            {
              permissionId: 1,
              permissionName: '系统管理',
              permission: 'system',
              icon: 'icon-system',
              createTime: '2023-01-01 00:00:00',
              hasChildren: true,
              children: [
                {
                  permissionId: 101,
                  permissionName: '用户管理',
                  permission: 'user',
                  icon: 'icon-user',
                  createTime: '2023-01-01 00:00:00',
                  hasChildren: false,
                  children: []
                },
                {
                  permissionId: 102,
                  permissionName: '角色管理',
                  permission: 'role',
                  icon: 'icon-role',
                  createTime: '2023-01-01 00:00:00',
                  hasChildren: false,
                  children: []
                }
              ]
            },
            {
              permissionId: 2,
              permissionName: '内容管理',
              permission: 'content',
              icon: 'icon-content',
              createTime: '2023-01-01 00:00:00',
              hasChildren: false,
              children: []
            }
          ]
          total.value = tableData.value.length
        }
      } else {
        ElMessage({ message: res.message || '获取菜单列表失败', type: 'error' })
      }
    } catch (error) {
      console.error('获取菜单列表失败:', error)
      ElMessage({ message: '获取菜单列表失败', type: 'error' })
    } finally {
      loading.value = false
    }
  }

  // 切换行选中状态
  const toggleSelection = (row, select) => {
    if (row) {
      nextTick(() => {
        tableRef.value && tableRef.value.toggleRowSelection(row, select)
      })
    }
  }
</script>

<style lang="scss" scoped>
  .setup-menu-container {
    padding: 20px;
    margin-top: 20px;
    background-color: var(--art-bg-color);

    .search-form {
      margin-bottom: 20px;
    }

    .table-actions {
      display: flex;
      gap: 10px; // 添加间距
    }

    :deep(.placeholder) {
      .el-input__inner {
        color: var(--el-text-color-placeholder);
      }
    }

    /* 复选框对勾图标绝对居中方案 */
    // 使用负边距和50%定位实现完美居中
    :deep(.el-checkbox__input.is-checked .el-checkbox__inner::after) {
      /* 绝对定位到中心 */
      left: 50% !important;
      top: 50% !important;
      /* 使用负边距进行精确调整 - 减少负上边距使对勾上移 */
      margin-left: -2px !important;
      margin-top: -4.5px !important;
      /* 只保留旋转 */
      transform: rotate(45deg) !important;
      position: absolute !important;
      
      /* 设置对勾样式 */
      border-width: 2px !important;
      border-left: 0 !important;
      border-top: 0 !important;
      content: '' !important;
      /* 精确尺寸 */
      width: 4px !important;
      height: 8px !important;
      
      /* 移除所有可能干扰的样式 */
      transition: none !important;
    }
    
    // 确保表格中的复选框对勾也使用相同的居中方法
    :deep(.el-table .el-checkbox__input.is-checked .el-checkbox__inner::after) {
      left: 50% !important;
      top: 50% !important;
      margin-left: -2px !important;
      margin-top: -4.5px !important;
    }
    
    // 确保复选框本身正确定位
    :deep(.el-table .el-checkbox__inner) {
      position: relative !important;
      width: 16px !important;
      height: 16px !important;
    }
  }

  // 响应式适配
  $device-notebook: 1600px;
  $device-ipad-pro: 1180px;
  $device-ipad: 800px;
  $device-ipad-vertical: 900px;
  $device-phone: 500px;

  // 平板横屏及更小屏幕
  @media screen and (max-width: #{$device-ipad-pro}) {
    .setup-menu-container {
      padding: 10px;
      margin-top: 10px;

      .search-form .el-form {
        display: flex;
        flex-direction: column;
        gap: 10px;
        align-items: flex-start;
      }

      .search-form .el-form-item {
        margin-bottom: 10px;
      }

      .search-form .el-form-item:nth-last-child(1) {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }

  // 平板竖屏及更小屏幕
  @media screen and (max-width: #{$device-ipad-vertical}) {
    .setup-menu-container {
      padding: 8px;
      margin-top: 8px;
    }

    // 调整对话框宽度
    :deep(.el-dialog) {
      width: 90% !important;
      max-width: 500px;
    }
  }

  // 手机屏幕
  @media screen and (max-width: #{$device-phone}) {
    .setup-menu-container {
      padding: 5px;
      margin-top: 5px;

      .search-form .el-input {
        width: 100% !important;
      }

      .table-actions {
        flex-direction: column;
        gap: 5px;
      }

      // 调整表格样式，确保内容能正常显示
      :deep(.el-table) {
        font-size: 12px;
      }

      :deep(.el-table__header th),
      :deep(.el-table__body td) {
        padding: 8px 4px;
      }
    }
  }
</style>
